from rest_framework.decorators import action
from rest_framework.response import Response
from dvadmin.utils.viewset import CustomModelViewSet
from .models import Budget, FinancialMetrics
from .serializers import BudgetSerializer, FinancialMetricsSerializer, BudgetCreateUpdateSerializer
from django.utils import timezone
from datetime import datetime, timedelta
from django.db.models import Q
import logging
from django.core.paginator import Paginator
from dvadmin.system.models import Dept

logger = logging.getLogger(__name__)

class BudgetViewSet(CustomModelViewSet):
    """
    预算管理视图集
    """
    queryset = Budget.objects.all()
    serializer_class = BudgetSerializer
    create_serializer_class = BudgetCreateUpdateSerializer
    update_serializer_class = BudgetCreateUpdateSerializer
    permission_classes = []  # 移除权限校验
    extra_filter_class = []  # 移除数据过滤器
    
    def get_queryset(self):
        queryset = super().get_queryset()
        create_date = self.request.query_params.get('create_datetime', None)
        
        logger.info(f"Received create_date: {create_date}")
        
        if create_date:
            try:
                filtered_queryset = queryset.extra(
                    where=[f"DATE(create_datetime) = '{create_date}'"]
                )
                logger.info(f"Original queryset count: {queryset.count()}")
                logger.info(f"Filtered queryset count: {filtered_queryset.count()}")
                
                return filtered_queryset.order_by('-create_datetime')
                
            except Exception as e:
                logger.error(f"Date filtering error: {e}")
                logger.exception(e)
        
        return queryset.order_by('-create_datetime')

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data
            for item in data:
                item['can_edit'] = item['status'] == 'pending'
                item['can_approve'] = item['status'] == 'pending'
                item['can_reject'] = item['status'] == 'pending'
                item['can_delete'] = item['status'] == 'pending'
            return self.get_paginated_response(data)

        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data
        for item in data:
            item['can_edit'] = item['status'] == 'pending'
            item['can_approve'] = item['status'] == 'pending'
            item['can_reject'] = item['status'] == 'pending'
            item['can_delete'] = item['status'] == 'pending'
        return Response(data)

    def create(self, request, *args, **kwargs):
        logger.info(f"创建预算请求数据: {request.data}")
        # 记录部门信息
        department_key = request.data.get('department')
        try:
            dept = Dept.objects.get(key=department_key)
            logger.info(f"找到部门: {dept.name} (key: {dept.key})")
        except Dept.DoesNotExist:
            logger.error(f"未找到部门: {department_key}")
        except Exception as e:
            logger.error(f"查询部门时发生错误: {str(e)}")
        
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        logger.info(f"更新预算请求数据: {request.data}")
        return super().update(request, *args, **kwargs)

    @action(detail=False, methods=['get'])
    def get_departments(self, request):
        """获取部门列表"""
        try:
            departments = Dept.objects.all()
            dept_list = []
            for dept in departments:
                dept_list.append({
                    'key': dept.key,
                    'name': dept.name,
                    'parent': dept.parent.key if dept.parent else None
                })
            logger.info(f"获取到的部门列表: {dept_list}")
            return Response({'code': 2000, 'msg': 'success', 'data': dept_list})
        except Exception as e:
            logger.error(f"获取部门列表失败: {str(e)}")
            return Response({'code': 4000, 'msg': f'获取部门列表失败: {str(e)}'}, status=500)
    
    @action(detail=True, methods=['post'])
    def approve(self, request, pk=None):
        """审批通过"""
        try:
            instance = self.get_object()
            if instance.status != 'pending':
                return Response({'status': 'error', 'message': '只能审批待处理的预算'}, status=400)
            
            instance.status = 'approved'
            instance.save()
            return Response({'status': 'success', 'message': '审批通过成功'})
        except Exception as e:
            return Response({'status': 'error', 'message': str(e)}, status=400)
    
    @action(detail=True, methods=['post'])
    def reject(self, request, pk=None):
        """审批拒绝"""
        try:
            instance = self.get_object()
            if instance.status != 'pending':
                return Response({'status': 'error', 'message': '只能审批待处理的预算'}, status=400)
            
            instance.status = 'rejected'
            instance.save()
            return Response({'status': 'success', 'message': '审批拒绝成功'})
        except Exception as e:
            return Response({'status': 'error', 'message': str(e)}, status=400)

class FinancialMetricsViewSet(CustomModelViewSet):
    """
    财务指标视图集
    """
    queryset = FinancialMetrics.objects.all()
    serializer_class = FinancialMetricsSerializer
    permission_classes = []  # 移除权限校验
    extra_filter_class = []  # 移除数据过滤器
 